package com.tanhua.server.controller;


import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.LikeCount;
import com.tanhua.model.dto.UserDto;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.intercepter.UserThreadLocal;
import com.tanhua.server.service.SettingsService;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserServise;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserServise userServise;


    /**
     * 查询用户或自己详情信息
     *
     * @param token
     * @param userID
     * @return
     */
    @GetMapping
    public ResponseEntity users(@RequestHeader("Authorization") String token, Long userID) {

        //获取线程里的id
        Long userId = UserThreadLocal.getUserId();
        //判断是否传入id,当userID为null就从调用自己id,查询自己的详情
        // 不为null就是查询其他用户信息
        if (null == userID) {
            userID = userId;
        }
        UserInfoVo userInfo = userInfoService.findById(userID);
        return ResponseEntity.ok(userInfo);
    }


    /**
     * 修改用户详情信息
     *
     * @param userInfo
     * @return
     */
    @PutMapping
    public ResponseEntity update(@RequestBody UserInfo userInfo) {
        /*//1.判断token是否合法
        boolean bToken = JwtUtils.verifyToken(token);
        if (!bToken) {
            return ResponseEntity.status(401).body(null);
        }
        //2.获取token中的用户信息
        Claims claims = JwtUtils.getClaims(token);
        String id = claims.get("id").toString();*/

        //1.校验token,从线程当中获取id
        Long userId = UserThreadLocal.getUserId();
        userInfo.setId(Long.valueOf(userId));

        //调用service更新数据
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);

    }

    /**
     * 更新头像
     */
    @PostMapping("/header")
    public ResponseEntity updateHead(MultipartFile headPhoto) {

        //1.从线程当中获取id
        Long userId = UserThreadLocal.getUserId();

        //2.调用service
        try {
            userInfoService.updateHead(headPhoto, userId);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
        return ResponseEntity.ok(null);
    }


    /**
     * 修改手机号码:1,发送短信验证码
     */
    @PostMapping("/phone/sendVerificationCode")
    public ResponseEntity sendVerificationCode() {
        userServise.sendSmsCode();
        return ResponseEntity.ok(null);
    }


    /**
     * 修改手机号2:校验验证码
     */
    @PostMapping("/phone/checkVerificationCode")
    public ResponseEntity checkVerificationCode(@RequestBody UserDto userDto) {
        //1.获取验证码
        String code = userDto.getVerificationCode();
        //2.调用service判断验证码并返回boolean值
        return userServise.checkVerificationCode(code);
    }

    /**
     * 修改手机号3:保存手机号码到数据库
     */
    @PostMapping("/phone")
    public ResponseEntity updatePhone(@RequestBody UserDto userDto) {

        //获取电话号码
        String phone = userDto.getPhone();
        //检验参数
        if (phone == null) {
            throw new BusinessException(ErrorResult.error());
        }
        //调用service保存手机号码
        userServise.updatePhone(phone);
        return ResponseEntity.ok(null);
    }

    /**
     * 是否喜欢
     *
     * @param id
     * @return
     */
    @GetMapping("/{uid}/alreadyLove")
    public ResponseEntity alreadyLove(@PathVariable Long id) {
        Boolean result = userServise.alreadyLove(id);
        return ResponseEntity.ok(result);
    }


    /**
     * 我的-统计 互相喜欢、喜欢、粉丝 数量
     * GET /users/counts
     */
    @GetMapping("/counts")
    public ResponseEntity counts() {
        LikeCount counts = userServise.counts();
        return ResponseEntity.ok(counts);
    }

    /**
     * 我的-查询 互相喜欢、喜欢、粉丝 列表
     * GET/users/friends/:type
     * type说明：
     *      值1：要查询  互相关注
     *      值2：要查询  我关注
     *      值3：要查询  粉丝
     *      值4：要查询  访客列表
     */
    @GetMapping("/friends/{type}")
    public ResponseEntity queryLikeList(@PathVariable("type") Integer type,
                                        @RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer pagesize,
                                        @RequestParam(required = false) String nickname){
        return userInfoService.queryLikeList(type,page,pagesize,nickname);
    }

    /**
     * 我的-粉丝-喜欢
     * POST /users/fans/:uid
     */
    @PostMapping("/fans/{id}")
    public ResponseEntity likeFans(@PathVariable("id") Long targetUserId){
        return userInfoService.likeFans(targetUserId);
    }

    /**
     * 我的-取消喜欢
     * DELETE /users/like/:uid
     */
    @DeleteMapping("/like/{id}")
    public ResponseEntity removeLike(@PathVariable("id") Long targetUserId){
        return userInfoService.removeLike(targetUserId);
    }

}
